//
//  ByPhotoPickerViewController.m
//  beibei_ios
//
//  Created by mc on 16/5/7.
//  Copyright © 2016年 hebidu. All rights reserved.
//

#import "ByPhotoPickerViewController.h"
#import <AVFoundation/AVFoundation.h>


#define VIDEOCELL @"videoCell"
#define ALBUMCELL @"albumCell"

#define iOS8            [[[UIDevice currentDevice]systemVersion]floatValue] >=8.0

@implementation ByVideoPickerCell

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        UIImageView *imageView = [[UIImageView alloc] init];
        [self addSubview:imageView];
        imageView.image = [UIImage imageNamed:@"照相机"];
        imageView.backgroundColor = BY_THEME_COLOR;     // 暂时测试使用
        imageView.frame = self.bounds;
        imageView.userInteractionEnabled = YES;
    }
    return self;
}


@end



@interface ByAlbumPickerCell()

@property (strong, nonatomic)  UIImageView *imageContentView;
@property (nonatomic,strong) UIDynamicAnimator *animator;
@property (strong, nonatomic)  UIButton *maskView;


@end


@implementation ByAlbumPickerCell

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.imageContentView = [[UIImageView alloc] init];
        [self addSubview:_imageContentView];
        [self.imageContentView setBackgroundColor:BY_THEME_COLOR];
        _imageContentView.frame = self.bounds;
        _imageContentView.userInteractionEnabled = YES;
        
        self.selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self addSubview:_selectButton];
        [_selectButton setImage:[UIImage imageNamed:@"选中 (2)"] forState:UIControlStateNormal];
        [_selectButton setImage:[UIImage imageNamed:@"选中 (1)"] forState:UIControlStateSelected];
        CGFloat x = SCREEN_WIDTH - 7 - 20;
        _selectButton.frame = CGRectMake(x, 7, 20, 20);
        self.selectButton.userInteractionEnabled = YES;
        
        
    }
    return self;
}

- (void)setAsset:(ALAsset *)asset
{
    _asset = asset;
    _imageContentView.image = [UIImage imageWithCGImage:[asset thumbnail]];
}

- (void)setTick:(BOOL)tick
{
    _tick = tick;
    self.selectButton.selected = tick;
}



- (UIImageView *)containerImageView
{
    return self.imageContentView;
}


@end

@interface ByPhotoPickerViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>{
    
    dispatch_queue_t _imagePickerQueue;
    NSMutableDictionary *_selectedRowOrders;
    ALAssetsLibrary *_assetsLibrary;
    dispatch_group_t _imagePickerGroup;
}
@property(nonatomic,strong) UIImagePickerController *pickerController;

@property(nonatomic,strong) UICollectionView *collectionView;

//相册相关
@property(nonatomic,strong) NSMutableArray *assets;
@property(nonatomic,strong) NSMutableArray *selectedAssets;//已经选择的图片
@property(nonatomic,strong) NSMutableArray *assetsURL;
@property(nonatomic,strong) NSMutableSet *selectedThumbImages;
@property(nonatomic,strong) NSMutableSet *selectedAssetURLs;
@property(nonatomic,strong) NSMutableArray *assetGroup;
@property(nonatomic,strong) NSMutableSet *selectedRow;
@property(nonatomic,strong) ALAsset *imagePickerAsset;

//底部视图
@property(nonatomic,strong) UIView *toolBar;
@property(nonatomic,strong) UILabel *toolBarLabel;
@property(nonatomic,strong) UIButton *toolBarButton;


@end

@implementation ByPhotoPickerViewController


- (instancetype)init
{
    self = [super init];
    if (self) {

        [self setupBasicParams];
    }
    return self;
}


- (void) setupBasicParams
{
    _imagePickerQueue = dispatch_queue_create("_imagePickerQueue", DISPATCH_QUEUE_PRIORITY_DEFAULT);
    _selectedRowOrders = [NSMutableDictionary dictionary];
    _assetsURL = [NSMutableArray array];
    _selectedThumbImages = [NSMutableSet set];
    _selectedAssetURLs = [NSMutableSet set];
    _assetsLibrary = [[ALAssetsLibrary alloc] init];
    _imagePickerGroup = dispatch_group_create();
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)didEnterForeground : (id)sender
{
    [self fetchAssetGroup];
    [self fetchAssetFromGroup:nil];
}





- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    
    self.title = @"照片选择";
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
    [self _createCollectionView];
    
    [self.view addSubview:self.toolBar];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterForeground:) name:UIApplicationDidBecomeActiveNotification object:nil];

    [self albumAuthDetact];
    
    // Do any additional setup after loading the view.
}


//获取相册信息
- (void)viewWillAppear:(BOOL)animated
{
        [super viewWillAppear:YES];
        [self fetchAssetGroup];
        [self fetchAssetFromGroup:nil];
}




- (void)_createCollectionView {
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 5;
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 0, 5);
    CGFloat height = (SCREEN_WIDTH - 25) / 4.0;
    // 设置单元格尺寸
    flowLayout.itemSize = CGSizeMake(height, height);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49) collectionViewLayout:flowLayout];
    [self.view addSubview:_collectionView];
    // 设置代理和数据源方法
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.scrollEnabled = YES;
    _collectionView.userInteractionEnabled = YES;
    //给集合视图注册一个类型的cell
    [_collectionView registerClass:[ByVideoPickerCell class] forCellWithReuseIdentifier:VIDEOCELL];
    [_collectionView registerClass:[ByAlbumPickerCell class] forCellWithReuseIdentifier:ALBUMCELL];
}


- (UIView *)toolBar
{
    if (!_toolBar) {
        _toolBar = [[UIView alloc] initWithFrame:CGRectMake(0, self.collectionView.bottom, SCREEN_WIDTH, 49)];
        _toolBar.backgroundColor = [UIColor whiteColor];
        _toolBarLabel = [[UILabel alloc] initWithFrame:CGRectMake(20 , 1, 120, 48)];
        _toolBarLabel.textColor = BY_THEME_COLOR;
        [_toolBarLabel setText:[NSString stringWithFormat:@"%lu/%li",(unsigned long)self.selectedAssets.count,(long)self.maxSelectedCount]];
        _toolBarButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_toolBarButton setTitle:@"确定" forState:UIControlStateNormal];
        [_toolBarButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_toolBarButton addTarget:self action:@selector(doneAction:) forControlEvents:UIControlEventTouchUpInside];
        [_toolBarButton setBackgroundColor:BY_THEME_COLOR];
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(_toolBar.bounds), 1)];
        lineView.backgroundColor = [UIColor lightGrayColor];
        [_toolBar addSubview:lineView];
        [_toolBar addSubview:_toolBarLabel];
        [_toolBar addSubview:_toolBarButton];
        CGFloat x = SCREEN_WIDTH - 100 - 10;
        CGFloat y = 9;
        _toolBarButton.frame = CGRectMake(x, y, 100, 30);

    }
    return _toolBar;
}

- (NSMutableArray *)assets
{
    if (!_assets) {
        _assets = [NSMutableArray array];
    }
    return _assets;
}



- (NSMutableArray *)selectedAssets
{
    if (!_selectedAssets) {
        _selectedAssets = [NSMutableArray array];
    }
    return _selectedAssets;
}


- (UIImagePickerController *)pickerController
{
    if (!_pickerController) {
        _pickerController = [[UIImagePickerController alloc] init];
        _pickerController.delegate = self;
    }
    return _pickerController;
}





#pragma mark 确定按钮
- (void)doneAction:(UIButton *)button{
        if (self && [self.delegate respondsToSelector : @selector(didSelectedAssets:)]){
            NSLog(@"选中的照片个数为  %lu",(unsigned long)self.selectedAssets.count);
            [self.delegate didSelectedAssets:self.selectedAssets];
        }
    
    
     [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.assets.count + 1;
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        ByVideoPickerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:VIDEOCELL forIndexPath:indexPath];
        return cell;
    }else{
        ByAlbumPickerCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:ALBUMCELL forIndexPath:indexPath];
        cell.asset = self.assets[indexPath.row - 1];
        if (/*[self.selectedRow containsObject:@(indexPath.row)]*/[self.selectedAssets containsObject:cell.asset]) {
            cell.tick = YES;
        } else {
            cell.tick = NO;
        }
        
        [cell.selectButton addTarget:self action:@selector(selectAction: event:) forControlEvents:UIControlEventTouchUpInside];
        return cell;

    }
}

#pragma mark UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 0) {
        
        
        if ([self albumAuthDetact] && [self cameraAuthDetact]) {
            BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
            if (isCameraAvailable) {
                self.pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:self.pickerController animated:YES completion:nil];
            }
        }

        
        
    }else{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            ByAlbumPickerCell *cell = (ByAlbumPickerCell *)[collectionView cellForItemAtIndexPath:indexPath];
            ALAsset *asset = self.assets[indexPath.row - 1];
            if (self.selectedAssets.count >= self.maxSelectedCount && ![self.selectedAssets containsObject:asset] ) {
                return;
            }
            BOOL tick = !cell.tick;
            
            if (tick) {
                [self.selectedAssets addObject:asset];
                NSURL *url = [asset valueForProperty:ALAssetPropertyAssetURL];
                [self.selectedAssetURLs addObject:url.absoluteString];
                [self.selectedRow addObject:@(indexPath.row)];
            } else {
                [self.selectedAssets removeObject:asset];
                NSURL *url = [asset valueForProperty:ALAssetPropertyAssetURL];
                [self.selectedAssetURLs removeObject:url.absoluteString];
                [self.selectedRow removeObject:@(indexPath.row)];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                cell.tick = tick;
                [collectionView reloadItemsAtIndexPaths:@[indexPath]];
                if ([self.delegate respondsToSelector:@selector(didSelectImageCount:)]) {
                    [self.delegate didSelectImageCount:self.selectedAssets.count];
                }
                [self updateToolbarState];
            });
            
        });

    }
    

}


- (void)setMaxSelectedCount:(NSInteger)maxSelectedCount
{
    _maxSelectedCount = maxSelectedCount;
     [self updateToolbarState];
}


- (void)updateToolbarState
{
    //if (self.selectedAssets.count > 0) {
        _toolBarButton.enabled = YES;
//    } else {
//        _toolBarButton.enabled = NO;
//    }
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%lu / %lu",(unsigned long)self.selectedAssets.count,(long)self.maxSelectedCount]];
    [text addAttributes:@{NSForegroundColorAttributeName : BY_THEME_COLOR,NSFontAttributeName : [UIFont systemFontOfSize:20]} range:NSMakeRange(0, [NSString stringWithFormat:@"%lu",self.selectedAssets.count].length)];
    NSInteger maxCountLenght = [NSString stringWithFormat:@"%lu",self.maxSelectedCount].length;
    [text addAttributes:@{NSForegroundColorAttributeName : BY_THEME_COLOR,NSFontAttributeName : [UIFont systemFontOfSize:14]} range:NSMakeRange(text.length - maxCountLenght,maxCountLenght)];
    [text addAttributes:@{NSForegroundColorAttributeName : BY_THEME_COLOR,NSFontAttributeName : [UIFont systemFontOfSize:14]} range:[[text string] rangeOfString:@"/"]];
    self.toolBarLabel.attributedText = text;
}



- (void)selectAction:(UIButton *)button event:(UIEvent*)event{
    UITouch * touch = [[event allTouches] anyObject];
    CGPoint point = [touch locationInView:self.collectionView];
    NSIndexPath * indexPath = [self.collectionView indexPathForItemAtPoint:point];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        ByAlbumPickerCell *cell = (ByAlbumPickerCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
        ALAsset *asset = self.assets[indexPath.row - 1];
        if (self.selectedAssets.count >= self.maxSelectedCount && ![self.selectedAssets containsObject:asset] ) {
            return;
        }
        BOOL tick = !cell.tick;
        
        if (tick) {
            [self.selectedAssets addObject:asset];
            NSURL *url = [asset valueForProperty:ALAssetPropertyAssetURL];
            [self.selectedAssetURLs addObject:url.absoluteString];
            [self.selectedRow addObject:@(indexPath.row)];
        } else {
            [self.selectedAssets removeObject:asset];
            NSURL *url = [asset valueForProperty:ALAssetPropertyAssetURL];
            [self.selectedAssetURLs removeObject:url.absoluteString];
            [self.selectedRow removeObject:@(indexPath.row)];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            cell.tick = tick;
            button.selected = cell.tick;
            [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
            if ([self.delegate respondsToSelector:@selector(didSelectImageCount:)]) {
                [self.delegate didSelectImageCount:self.selectedAssets.count];
            }
            [self updateToolbarState];
        });
        
    });

    
    
}




- (BOOL)canOpenAssertsLibrary
{
    ALAuthorizationStatus authStatus = [ALAssetsLibrary authorizationStatus];
    return authStatus == ALAuthorizationStatusAuthorized || authStatus == ALAuthorizationStatusNotDetermined ? YES : NO;
}

#pragma mark --- 权限检测
- (BOOL) albumAuthDetact
{
    if (![self canOpenAssertsLibrary]) {
            [UIAlertView showWithTitle:@"无法使用相册" message:@"请在iPhone的”设置-贝贝-相册“选项中，允许贝贝访问你的相册。" cancelButtonTitle:@"取消" otherButtonTitles:@[@"去设置"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if(buttonIndex == 1){
                if (iOS8) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                } else {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=General"]];
                }
            }
        }];
        return NO;
    }
    return YES;
}


- (BOOL)canCaptureVideo
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType : AVMediaTypeVideo];
    return  authStatus == AVAuthorizationStatusAuthorized || authStatus == AVAuthorizationStatusNotDetermined? YES : NO;
}



- (BOOL) cameraAuthDetact
{
    if (![self canCaptureVideo]) {
        [UIAlertView showWithTitle:@"无法使用相册" message:@"请在iPhone的”设置-萌屋-相机“选项中，允许萌屋访问你的相机。" cancelButtonTitle:@"取消" otherButtonTitles:@[@"去设置"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if(buttonIndex == 1){
                if (iOS8) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                } else {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=General"]];
                }
            }
        }];
        return NO;
    }
    return YES;
}






-(void)fetchAssetGroup
{
    
    [self.assetGroup removeAllObjects];
    [_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
        if (group) {
            [self.assetGroup addObject:group];
        } else {
        }
    } failureBlock:^(NSError *error) {
        NSLog(@"Group not found!\n");
    }];
}


- (void)fetchAssetFromGroup : (ALAssetsGroup *) assetsGroup
{
    [self.assets removeAllObjects];
    [self.selectedAssets removeAllObjects];
    [self.selectedRow removeAllObjects];
    
//    ALAsset *asset = [[ALAsset alloc] init];
//    [self.assets addObject:asset];
    dispatch_async(_imagePickerQueue, ^{
        [_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
            //如果assetsGroup == nil  默认取 ALAssetsGroupSavedPhotos
            if ((assetsGroup == nil && [[group valueForProperty:ALAssetsGroupPropertyType] isEqualToNumber:[NSNumber numberWithInt:ALAssetsGroupSavedPhotos]])|| [[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:[assetsGroup valueForProperty:ALAssetsGroupPropertyName]]) {
                [group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock: ^(ALAsset *result, NSUInteger index, BOOL *stop) {
                    if (result) {
                        [self.assets addObject:result];
                        [self.assetsURL addObject:[result valueForProperty:ALAssetPropertyAssetURL]];
                        NSURL *url = [result valueForProperty:ALAssetPropertyAssetURL];
                        if ([self.selectedAssetURLs containsObject:url.absoluteString]) {
                            [self.selectedAssets addObject:result];
                        }
                    }
                }];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.collectionView reloadData];
                });
                *stop = YES;
            }
        } failureBlock:^(NSError *error) {
            NSLog(@"Group not found!\n");
        }];
    });
}




#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        //如果是拍照获得的图片 就把图片存到相片库中
        UIImage * image =  [info objectForKey:UIImagePickerControllerOriginalImage];
        

        [_assetsLibrary writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error) {
           
            if (error) {
                [self pickerVCDone];
            }
            [_assetsLibrary assetForURL:assetURL resultBlock:^(ALAsset *asset) {
                if (asset) {
                    if ([self.delegate respondsToSelector:@selector(didFinishPickingCameraPhoto:)]) {
                        [self.delegate didFinishPickingCameraPhoto:asset];
                    }
                    
                    self.imagePickerAsset = asset;
                    [self.selectedAssets addObject:self.imagePickerAsset];
                    [self updateToolbarState];
                    if (self.selectedAssets.count <= self.maxSelectedCount) {
                        NSURL *url = [asset valueForProperty:ALAssetPropertyAssetURL];
                        [self.selectedAssetURLs addObject:url.absoluteString];
                    }
                    
                }
                [self pickerVCDone];
            } failureBlock:^(NSError *error){
                [self pickerVCDone];
            }];
        }];
        
    }else {
        
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    [self doneAction:nil];
}


- (void)pickerVCDone
{
    [self.pickerController dismissViewControllerAnimated:NO completion:^{
       
    
    
    }];
    
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    
    
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
